package com.cardone.platform.common.function;

import com.cardone.common.cache.util.CacheUtils;
import com.cardone.context.ContextHolder;
import com.cardone.context.function.Execution1Function;
import com.cardone.platform.common.dto.EntityLogDto;
import com.cardone.platform.common.service.EntityLogService;
import com.cardone.security.token.dto.TokenDto;
import com.cardone.security.token.util.TokenUtils;
import com.google.common.collect.Maps;

import java.util.Map;

/**
 * Created by c100000002 on 15-2-6.
 */
public class TokenGetFunction implements Execution1Function<TokenDto, String> {
    @Override
    public TokenDto execution(String tokenKey) {
        return CacheUtils.get(TokenUtils.class.getName(), tokenKey, () -> {
            Map<String, Object> findEntityLogMap = Maps.newHashMap();

            findEntityLogMap.put("id", tokenKey);
            findEntityLogMap.put("dataStateCode", "activity");

            EntityLogDto entityLog = ContextHolder.getBean(EntityLogService.class).findByCode(EntityLogDto.class, findEntityLogMap);

            if (entityLog == null) {
                return null;
            }

            TokenDto token = new TokenDto();

            token.setId(entityLog.getUserId()).setClientId(entityLog.getClientId()).setCreateDate(entityLog.getCreatedDate());
            token.setCode(entityLog.getCode()).setKey(tokenKey);

            return token;
        });
    }
}
